package com.liuqi.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuqi.entity.Menu;
import com.liuqi.entity.Role;
import com.liuqi.entity.RoleMenu;
import com.liuqi.mapper.RoleMapper;
import com.liuqi.mapper.RoleMenuMapper;
import com.liuqi.service.MenuService;
import com.liuqi.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private MenuService menuService;

    @Transactional//事务注解，提交事务，保证两步骤同时成功
    @Override
    public void setRoleMenu(Integer roleId, List<Integer> menuIds) {
        //1.先删除当前角色id所有的绑定关系
        //方式一：使用mybatis-plus分支好的方法进行删除操作
        /*QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        roleMenuMapper.delete(queryWrapper);*/
        //方式二：直接写sql语句
        roleMenuMapper.deleteByRoleId(roleId);

        //2.再把前端传过来的菜单id数组绑定到当前角色id上
        List<Integer> menuIdsCopy = CollUtil.newArrayList(menuIds);
        for (Integer menuId : menuIds) {
            Menu menu = menuService.getById(menuId);
            if(menu.getPid()!=null&&!menuIdsCopy.contains(menu.getPid())){//二级权限菜单 并且传过来的menuId数组里面没有它的父级id
                //那么就得不上父级id
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menu.getPid());
                roleMenuMapper.insert(roleMenu);
                menuIdsCopy.add(menu.getPid());
            }

            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuMapper.insert(roleMenu);


        }
    }
    @Override
    public List<Integer> getRoleMenu(Integer roleId) {
        return roleMenuMapper.selectByRoleId(roleId);
    }
}
